//
//  HMHomeViewModel.swift
//  HMSlender
//
//  Created by 赵少朋赵少朋 on 2017/2/4.
//  Copyright © 2017年 ITheima. All rights reserved.
//

import UIKit
import SDWebImage

class HMHomeViewModel: NSObject {

    var dataArray:[HMStatusViewModel] = [HMStatusViewModel()]
    
    func loadHomeData( isPullUp:Bool,isFinish:@escaping (Bool, Int)->()) -> Void {
        
        var sinceId:Int64 = 0
        var maxId:Int64 = 0
        
        /// 判断是否为上啦刷新
        if isPullUp {
            
            // 是上啦刷新就请求maxId 最新的数据
            maxId = dataArray.last?.homeModle?.id ?? 0
        } else {
            //是下拉刷新就更新sinceId 数据数组第一个数据id
            sinceId = dataArray.first?.homeModle?.id ?? 0
        }
        
        
        NetworkTools.sharedNetworkTools.loadHomeDataInfo(maxId: maxId, sinceId: sinceId, success: { (response) in
            
            guard let res = response as? [String : Any] else {
                
                isFinish(false, 0)
                return
            }
            
            let statusArray = NSArray.yy_modelArray(with: HMHomeModel.self, json: res["statuses"] ?? "") as! [HMHomeModel]
//            print(tempArray,tempArray.count)
            // 创建可变数组
            var arrayM:[HMStatusViewModel] = [HMStatusViewModel]()
            
            // 实例化调度组
            let group = DispatchGroup()
            
            for homeModel in statusArray {
                
                /// 判断微博的图片是否是单张图片 是单张图片就下载
                if homeModel.pic_urls?.count == 1 {
                    
                    //调度组进入
                    group.enter()
                    SDWebImageManager.shared().downloadImage(with: URL(string:homeModel.pic_urls?.first?.thumbnail_pic ?? ""), options: [], progress: nil, completed: { (image, error, _, _, _) in
                        
                        print("单张图片下载完成")
                        // 调度组出去
                        group.leave()
                    })
                    
                }
                
                if homeModel.retweeted_status?.pic_urls?.count == 1 {
                
                    // 调度组进去
                    group.enter()
                    SDWebImageManager.shared().downloadImage(with: URL(string:homeModel.pic_urls?.first?.thumbnail_pic ?? ""), options: [], progress: nil, completed: { (image, error, _, _, _) in
                        
                        print("单张图片下载完成")
                        // 调度组出去
                        group.leave()
                    })
                }
                
                let statusView = HMStatusViewModel()
                statusView.homeModle = homeModel
                arrayM.append(statusView)
            }
            //上啦
            if isPullUp {
                self.dataArray = self.dataArray + arrayM
            } else {
                self.dataArray = arrayM + self.dataArray
            }
            /// 调度组内的数据下载完成以后 回到主线程 执行指定代码
            group.notify(queue: DispatchQueue.main, execute: {
                
                isFinish(true, arrayM.count)
            })
            

        }, failure: {(error)->() in
            
            if let err = error {
                isFinish(false, 0)
                print("失败",err)
            }
            
        })
        
        
    }
    
}

